package handler

// func newProxyHandler() {

// }

// package handler

import (
	"fmt"
	"iptv_server/v3/v2_src/handler/middleware"
	"net/http"
	"strconv"
)

func initStatusCode(mux *http.ServeMux, middles ...middleware.MiddleWare) {
	vs := [...]int{
		http.StatusOK, http.StatusCreated, http.StatusAccepted,
		http.StatusMovedPermanently, http.StatusFound, http.StatusSeeOther, http.StatusNotModified,
		http.StatusNotFound,
	}

	for _, v := range vs {
		h := middleware.ApplyMiddles(&code{v}, middles...)
		mux.Handle(fmt.Sprintf("/api/code/%d", v), h)
	}

	h := middleware.ApplyMiddles(&urlReturnCode{}, middles...)
	mux.Handle("/api/checkurl", h)
	mux.Handle("/api/checkurl/", h)

}

type code struct {
	i int
}

// "/api/code/"
// "0:/1:api/2:code/3:"
func (c *code) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	switch c.i {
	case http.StatusOK:
		w.WriteHeader(c.i)
		w.Write([]byte("Hello world peace\n"))
		w.Write([]byte("your address is ="))
		w.Write([]byte(r.RemoteAddr))
		w.Write([]byte("\n"))
	case http.StatusFound:
		fallthrough
	case http.StatusMovedPermanently:
		w.Header().Add("Location", "/api/code/200")
		w.WriteHeader(c.i)
	}

}

type urlReturnCode struct {
}

// "/api/code/"
// "0:/1:api/2:code/3:"
func (h *urlReturnCode) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)

	_ = r.ParseForm()
	u := r.Form.Get("url")
	if len(u) <= 0 {
		w.Write([]byte("400"))
		return
	}

	client := &http.Client{
		CheckRedirect: func(req *http.Request, via []*http.Request) error {
			return http.ErrUseLastResponse
		},
	}

	resp, err := client.Head(u)
	if err != nil {
		w.Write([]byte("400"))
		return
	}
	defer resp.Body.Close()
	c := resp.StatusCode
	w.Write([]byte(strconv.Itoa(c)))
}
